package me.numark;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.model.User;
import me.numark.net.BaseResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.providers.Numa;
import me.numark.utils.Settings;
import me.numark.view.ContactsCursorBaseAdapter;
import me.numark.view.PinnedHeaderListView;

public class ContactsActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor>,
        AdapterView.OnItemClickListener, TextWatcher {

    @InjectView(R.id.title)
    TextView titleView;
    @InjectView(R.id.left_text)
    TextView leftTitleView;
    @InjectView(R.id.list)
    PinnedHeaderListView mList;
    @InjectView(R.id.search_edit)
    EditText searchBarEdit;

    ContactsAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        ButterKnife.inject(this);
        titleView.setText(getString(R.string.message_contacts));
        leftTitleView.setText(getString(android.R.string.cancel));
        leftTitleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mAdapter = new ContactsAdapter(this);
        mList.setAdapter(mAdapter);
        getLoaderManager().initLoader(0, null, this);
        mList.setOnItemClickListener(this);
        mList.setFastScrollEnabled(true);
        searchBarEdit.addTextChangedListener(this);
        loadUsers();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        String query = searchBarEdit.getText().toString().trim();
        String where = null;
        query = query.replaceAll("'", "");
        if (query.length() > 0) {
            where = "(nick LIKE '%" + query + "%')";
        }
        return new CursorLoader(this, Numa.UserColumns.CONTENT_URI, null,
                where,
                null, "pinyin asc");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        if (cursor == null) {
            return;
        }
        ArrayList<ContactsCursorBaseAdapter.Section> sections = new ArrayList<ContactsCursorBaseAdapter.Section>();
        int pos = 0;
        ContactsCursorBaseAdapter.Section s = null;
        while (cursor.moveToNext()) {
            String py = cursor.getString(cursor.getColumnIndex(Numa.UserColumns.USER_PINYIN));
            if (TextUtils.isEmpty(py)) {
                py = "{";
            }
            if (s == null || py.charAt(0) != s.firstChar) {
                s = new ContactsCursorBaseAdapter.Section();
                s.start = pos;
                s.count = 0;
                s.firstChar = py.charAt(0);
                s.header = String.valueOf((char) ('A' + s.firstChar - 'a'));
                if (s.firstChar == '{') {
                    s.header = "#";
                }
                sections.add(s);
            }
            pos++;
            s.count++;
        }
        mAdapter.updateData(cursor, sections);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        mAdapter.clear();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, ChatActivity.class);
        Cursor cursor = (Cursor) mAdapter.getItem(position);
        intent.putExtra(ChatActivity.EXTRA_USER_NICK, cursor.getString(cursor.getColumnIndex("nick")));
        intent.putExtra(ChatActivity.EXTRA_USER_AVATAR, cursor.getString(cursor.getColumnIndex("pic")));
        intent.putExtra(ChatActivity.EXTRA_USER_UID, cursor.getInt(cursor.getColumnIndex("_id")));
        finish();
        startActivity(intent);
    }

    void loadUsers() {
        String url = String.format(NetworkConstants.FOLLOWS_URL, Settings.getUid());
        Map<String, String> body = new LinkedHashMap<String, String>();
        GsonRequest<UsersListResponse> request = new GsonRequest<UsersListResponse>(url,
                Request.Method.GET, UsersListResponse.class, false, null, new Response.Listener<UsersListResponse>() {
            @Override
            public void onResponse(UsersListResponse response) {
                if (!response.ret) {
                    return;
                }
                ArrayList<ContentValues> values = new ArrayList<ContentValues>();
                for (User user : response.data) {
                    ContentValues cv = new ContentValues();
                    cv.put(Numa.UserColumns.USER_ID, user.uid);
                    cv.put(Numa.UserColumns.USER_NICK, user.nick);
                    cv.put(Numa.UserColumns.USER_DES, user.des);
                    cv.put(Numa.UserColumns.USER_FOLLOWS, user.follow);
                    cv.put(Numa.UserColumns.USER_FANS, user.fans);
                    cv.put(Numa.UserColumns.USER_IS_FOLLOW, user.is_follow);
                    cv.put(Numa.UserColumns.USER_IS_FAN, user.is_fans);
                    cv.put(Numa.UserColumns.USER_PIC, user.pic);
                    if (TextUtils.isEmpty(user.p_nick)) {
                        user.p_nick = "{";
                    } else {
                        user.p_nick = user.p_nick.toLowerCase();
                        char ch = user.p_nick.charAt(0);
                        if (ch < 'a' || ch > 'z') {
                            user.p_nick = "{" + user.p_nick;
                        }
                    }
                    cv.put(Numa.UserColumns.USER_PINYIN, user.p_nick);
                    values.add(cv);
                }
                getContentResolver().bulkInsert(Numa.UserColumns.CONTENT_URI,
                        values.toArray(new ContentValues[values.size()]));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        getLoaderManager().restartLoader(0, null, this);
    }

    public static class UsersListResponse extends BaseResponse {

        public boolean has_more;

        public User[] data;
    }

    class ContactsAdapter extends ContactsCursorBaseAdapter {
        public ContactsAdapter(Context context) {
            super(context, null);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
            return LayoutInflater.from(context).inflate(R.layout.contact_item, viewGroup, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            ImageView avatar = (ImageView) view.findViewById(R.id.avatar);
            Picasso.with(mContext).load(cursor.getString(cursor.getColumnIndex("pic"))).into(avatar);
            TextView tv = (TextView) view.findViewById(android.R.id.text1);
            tv.setText(cursor.getString(cursor.getColumnIndex("nick")));
            tv = (TextView) view.findViewById(android.R.id.text2);
            tv.setText(cursor.getString(cursor.getColumnIndex("des")));
        }
    }

}
